// pages/circle/circle.js
import { circle } from '../../server/circle';
import { file } from '../../server/file';
import { server } from '../../config/server';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        server_addr: server.server_addr,
        posts: [],
        // 发布圈子的小窗口
        addCircleBox: {
            showAddCircleBox: false,
            circleTitle: "",
            circleContent: "",
            selectedImage: ""
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getCircleList();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    // 获取圈子列表
    getCircleList() {
        circle.getCircle().then(async (res) => {
            let posts = [];
            for (let i = 0; i < res.data.length; i++) {
                let item = res.data[i];
                let imgUrl = await file.downloadPublicFile(item.photoId);
                imgUrl = imgUrl.data.url;
                let tmp = {
                    id: item.id,
                    title: item.title,
                    content: item.content,
                    date: item.time,
                    likes: item.likeCount,
                    comments: item.commentCount,
                    image: imgUrl
                };
                posts.push(tmp);
            }
            this.setData({ posts });
        }).catch((err) => {
            wx.showToast({
                title: '请检查网路',
                icon: 'none',
                duration: 1000
            });
        });
    },
    loadMore() {
        let lastId = this.data.posts[this.data.posts.length - 1].id;
        circle.getCircle(lastId).then(async (res) => {
            let posts = this.data.posts;
            for (let i = 0; i < res.data.length; i++) {
                let item = res.data[i];
                let imgUrl = await file.downloadPublicFile(item.photoId);
                imgUrl = imgUrl.data.url;
                let tmp = {
                    id: item.id,
                    title: item.title,
                    content: item.content,
                    date: item.time,
                    likes: item.likeCount,
                    comments: item.commentCount,
                    image: imgUrl
                };
                posts.push(tmp);
            }
            this.setData({ posts });
        }).catch((err) => {
            wx.showToast({
                title: '请检查网路',
                icon: 'none',
                duration: 1000
            });
        });
    },
    // 跳转到圈子详情页
    viewPost(e) {
        let circleid = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/circleInfo/circleInfo?circle='+circleid
        });
    },

    openAddCircleBox() {
        let addCircleBox = this.data.addCircleBox;
        addCircleBox.showAddCircleBox = true;
        this.setData({
            addCircleBox
        });
    },

    closeAddCircleBox() {
        let addCircleBox = this.data.addCircleBox;
        addCircleBox.showAddCircleBox = false;
        addCircleBox.circleTitle = "";
        addCircleBox.circleContent = "";
        addCircleBox.selectedImage = "";
        this.setData({
            addCircleBox
        });
    },

    inputCircleTitleFunc(e) {
        let addCircleBox = this.data.addCircleBox;
        addCircleBox.circleTitle = e.detail.value;
        this.setData({
            addCircleBox
        });
    },

    inputCircleContentFunc(e) {
        let addCircleBox = this.data.addCircleBox;
        addCircleBox.circleContent = e.detail.value;
        this.setData({
            addCircleBox
        });
    },

    // 选择图片的函数
    chooseImage() {
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'],    // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'],         // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
                const tempFilePaths = res.tempFilePaths;
                const fs = wx.getFileSystemManager();
                fs.readFile({
                    filePath: tempFilePaths[0],
                    encoding: 'base64',
                    success: (res) => {
                        const base64Data = res.data;
                        let addCircleBox = this.data.addCircleBox;
                        const fileType = tempFilePaths[0].match(/\.(\w+)$/)[1]; // 获取文件类型
                        const dataUrl = `data:image/${fileType};base64,${base64Data}`;
                        addCircleBox.selectedImage = dataUrl; // 存储Data URL
                        this.setData({
                            addCircleBox
                        });
                        console.log(addCircleBox);
                    },
                    fail: (err) => {
                        console.error('读取文件失败', err);
                    }
                });
            }
        });
    },

    checkNewCircleFunc(circleTitle, circleContent, selectedImage) {
        if (!circleTitle) {
            wx.showToast({
                title: '标题不能为空',
                icon: 'none',
                duration: 1000
            });
            return false;
        }
        if (!circleContent) {
            wx.showToast({
                title: '内容不能为空',
                icon: 'none',
                duration: 1000
            });
            return false;
        }
        if (!selectedImage) {
            wx.showToast({
                title: '图片不能为空',
                icon: 'none',
                duration: 1000
            });
            return false;
        }
        return true;
    },

    commitCircleBox() {
        // 获取用户输入的值
        let addCircleBox = this.data.addCircleBox;
        let circleTitle = addCircleBox.circleTitle;
        let circleContent = addCircleBox.circleContent;
        let selectedImage = addCircleBox.selectedImage;
        // 判断用户输入是否合法
        let flag = this.checkNewCircleFunc(circleTitle, circleContent, selectedImage);
        if (!flag) {
            return ;
        }
        // 调用后端接口
        circle.addCircle(circleTitle, circleContent, selectedImage).then((res) => {
            if (!res.success) {
                wx.showToast({
                    title: '发布圈子失败',
                    icon: 'none',
                    duration: 1000
                });
                return ;
            }
            wx.showToast({
                title: '发布圈子成功',
                icon: 'none',
                duration: 1000
            });
            this.closeAddCircleBox();
            this.getCircleList();
        }).catch((err) => {
            console.log(err);
            wx.showToast({
                title: '请检查网络连接',
                icon: 'none',
                duration: 1000
            });
        });
    }
})